<?php

namespace App\Models\Customer;

use App\Helpers\Code;
use App\Models\BaseModel;
use App\Models\Basic\DictionaryMember;
use App\Models\Basic\RegionProvince;
use Illuminate\Support\Facades\Auth;

class Customer extends BaseModel
{

    protected $table = 'customers';
    protected $fillable = [
        'title', 'code', 'description', 'charged_by', 'type', 'address', 'postcode', 'email', 'field', 'phone', 'region',
        'province', 'state', 'created_by', 'updated_by', 'data_scope',
    ];
    public $sorters = [];
    public $params = ['title', 'code', 'name'];

    public function departments()
    {
        return $this->hasMany('App\Models\Customer\CustomerDepartment', 'customer_id');
    }

    public function chargedBy()
    {
        return $this->belongsTo('App\Models\Account\User', 'charged_by');
    }

    public function region()
    {
        return $this->belongsTo('App\Models\Basic\Region', 'region');
    }

    public function province()
    {
        return $this->belongsTo('App\Models\Basic\RegionProvince', 'province');
    }

    public function createdBy()
    {
        return $this->belongsTo('App\Models\Account\User', 'created_by');
    }

    public function updatedBy()
    {
        return $this->belongsTo('App\Models\Account\User', 'updated_by');
    }

    public function type()
    {
        return $this->belongsTo('App\Models\Basic\DictionaryMember', 'type', 'code');
    }

    /**
     * 添加客户
     * @param $data
     * @return mixed
     */
    public function addCustomer($data)
    {
        //判断客户分类是否存在
        $type = DictionaryMember::whereHas('dictionary', function ($dictionary) {
            $dictionary->where('code', 'khlx');
        })->where('code', $data['type'])->count();
        if ($type < 1) {
            return null;
        }

        $code = $this->orderBy('code', 'desc')->limit(1)->first(['code']);

        if ($code) {
            $data['code'] = 'NC' . str_pad(substr($code->code, 2) + 1, 4, 0, STR_PAD_LEFT);
        } else {
            $data['code'] = 'NC0001';
        }

        $province = RegionProvince::where('region_id', $data['region'])->where('id', $data['province'])->count();
        if ($province < 1) {
            return Code::INSIDE_ERROR;
        }

        $userId = Auth::id();
        $data['created_by'] = $userId;
        $data['updated_by'] = $userId;
        $data['data_scope'] = $this->getDataScope();

        return $this->create($data);
    }

    /**
     * 编辑客户
     * @param $data
     * @param $id
     * @return null
     */
    public function editCustomer($data, $id)
    {
        $model = $this->find($id);

        if (!$model) {
            return null;
        }

        //判断客户分类是否存在
        $type = DictionaryMember::whereHas('dictionary', function ($dictionary) {
            $dictionary->where('code', 'khlx');
        })->where('code', $data['type'])->count();
        if ($type < 1) {
            return Code::INSIDE_ERROR_1;
        }

        $region = $data['region'] ?? $model->region;
        $province = $data['province'] ?? $model->province;
        $provinceCheck = RegionProvince::where('region_id', $region)->where('id', $province)->count();
        if ($provinceCheck < 1) {
            return Code::INSIDE_ERROR;
        }

        $data['updated_by'] = Auth::id();

        return $model->updateOrCreate(['id' => $id], $data);
    }

    /**
     * 获取客户及科室
     * @param $keyword
     * @return \Illuminate\Database\Eloquent\Collection|static[]
     */
    public function getCustomerTree($keyword)
    {
        $model = $this->with(['departments' => function ($department) {
            $department->where('state', 1)->select(['id', 'customer_id', 'title', 'code']);
        }]);

        if (isset($keyword)) {
            $model->where('code', 'like', '%' . $keyword . '%')
                ->orWhere('title', 'like', '%' . $keyword . '%');
        }

        return $model->where('state', 1)->get(['id', 'title', 'code']);
    }

    /**
     * 获取客户详情
     * @param $id
     * @return \Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Model|null|static|static[]
     */
    public function getCustomer($id)
    {
        $model = $this->with([
            'departments:id,customer_id,title,code,description,phone,email,state,field,salesman,region,province',
            'departments.region:id,title',
            'departments.province:id,title',
            'chargedBy:id,username',
            'updatedBy:id,username',
            'createdBy:id,username',
            'region:id,title',
            'province:id,title',
            'type:code,title',
        ])->find($id, ['title', 'code', 'description', 'charged_by', 'type', 'address', 'postcode', 'email', 'field', 'phone', 'region',
            'province', 'state', 'created_by', 'updated_by']);

        if (!$model) {
            return null;
        }

        return $model;
    }

    /**
     * 获取客户列表
     * @param $limit
     * @param $sorter
     * @param $search
     * @param $defaultSorter
     * @return mixed
     */
    public function getCustomerList($limit, $sorter, $search, $defaultSorter)
    {
        $perPage = $limit > 0 ? $limit : $this->limit;
        if ($defaultSorter == 'desc') {
            $model = $this->orderBy('created_at', $defaultSorter);
        } else {
            $model = $this->orderBy($sorter[0], $sorter[1]);
        }

        $model->select(['id', 'title', 'code', 'description', 'charged_by', 'type', 'address', 'postcode', 'email', 'field', 'phone', 'region',
            'province', 'state', 'created_by', 'created_at', 'updated_at'])
            ->with([
                'chargedBy:id,username',
                'createdBy:id,username',
                'region:id,title',
                'province:id,title',
                'type:code,title',
            ]);

        foreach ($search as $key => $value) {
            switch ($key) {
                case 'code':
                case 'title':
                    $model->where($key, 'like', '%' . $value . '%');
                    break;
                case 'name':
                    $model->whereHas('chargedBy', function ($charge) use ($value) {
                        $charge->where('username', 'like', '%' . $value . '%');
                    });
                    break;
            }
        }

        return $model->paginate($perPage)->toArray();
    }

    /**
     * 获取部门列表
     * @param $id
     * @return \Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Model|null|static|static[]
     */
    public function getCustomerDepartmentList($id)
    {
        $model = $this->with([
            'departments:id,customer_id,title,code,description,phone,email,state,field,salesman,region,province,created_by,updated_by,rank',
            'departments.region:id,title',
            'departments.province:id,title',
            'departments.salesman:id,username',
            'departments.field:code,title',
        ])->find($id, ['id', 'title']);

        if (!$model) {
            return null;
        }

        return $model;
    }
}
